<?php
/*
 * PASSPORT
 */
class Passport
{
    const _CONST_TB_DEFAULT_   = 'tg_passport';
    const _CONST_PASSPORT_SID_ = 'passport_sid';
    const _CONST_PASSPORT_LT_  = 86400;
	const _CONST_COOKIE_KEY_UID_ = 'passportUid';
	const _CONST_COOKIE_TIMEOUT_UID_ = 864000;

    public static function getCurrentUserUid ()
    {
	    $uid = Cookie::get(self::_CONST_COOKIE_KEY_UID_, NULL);
        return $uid;
    }

    public static function setCurrentUserUid ($uid)
    {
        if (empty($uid))
            Cookie::delete(self::_CONST_COOKIE_KEY_UID_);
        else
            Cookie::set(self::_CONST_COOKIE_KEY_UID_, $uid, self::_CONST_COOKIE_TIMEOUT_UID_);
        return $uid;
    }

    public static function getCurrentWeixinUserUid ()
    {
        include_once DOCROOT.'/resource/wxpay/lib/WxPay.Config.php';
        $options = array(
		    'token'=>'tokenaccesskey', //填写你设定的key
		    'appid'=> WxPayConfig::APPID, //填写高级调用功能的app id, 请在微信开发模式后台查询
		    'appsecret'=> WxPayConfig::APPSECRET, //填写高级调用功能的密钥
        );

        $wxUser   = new Passport_Wechat($options);
        $userInfo = $wxUser->getUserInfo();

        $userId     = Arr::get($userInfo, 'openid');
        $userId     = Arr::get($userInfo, 'unionid');
        $userName   = Arr::get($userInfo, 'nickname');
        $userIcon   = Arr::get($userInfo, 'headimgurl');
        $userGender = Arr::get($userInfo, 'sex');
        $userGender = $userGender == 1 ? 'm' : 'f';
        $source     = 'Wechat';
        $userToken  = '';
        $userPushId = NULL;


        $user = User::initUserFromBasicInfo ($source, $userId, $userToken,
            $userName, $userIcon, $userGender, $userPushId);

        $uid = $user->getUserUid();
        Cookie::set(self::_CONST_COOKIE_KEY_UID_, $uid, self::_CONST_COOKIE_TIMEOUT_UID_);
        return $uid;
    }
 

    /**
     * 当前passport用户的sid (唯一标识符)
     *
     * @return  string  $passport
     * @return  NULL    if invalid
     */
    public static function current_user_sid ()
    {
        return Cookie::get(self::_CONST_PASSPORT_SID_, NULL);
    }

    public static function has_email ($email)
    {
        if (self::count(array('passport' => $email)) > 0)
            return TRUE;
        else
            return FALSE;
    }

	/*
     * 注册新用户
     *
     * @param   string  $passport
     * @param   string  $passwd (raw passwd)
     * @return  boolean
	 */
	public function create ($passport, $password)
	{
        if (self::count(array('passport' => $passport)) > 0)
            return TRUE;
        else
        {
            $k = self::insert(array(
                'passport'   => $passport,
                'md5_passwd' => md5($password),
            ));
            return $k;
        }
	}


    /**
     * Login
     *
     * @param   string  $passport
     * @param   string  $passwd
     * @return  boolean
     */
    public function login ($passport, $passwd, $set_cookie = TRUE, $check_status = TRUE)
    {
        $query  = array('passport' => $passport, 'md5_passwd' => md5($passwd));
        if (self::count($query) > 0)
        {
            if ($check_status)
            {
                $user = User::factory($passport);
                if (! $user->is_activated())
                    return FALSE;
            }

            if ($set_cookie)
                Cookie::set(self::_CONST_PASSPORT_SID_, $passport, self::_CONST_PASSPORT_LT_);

            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    /**
     * Logout
     *
     * @return  boolean
     */
    public function logout ()
    {
        return Cookie::delete(self::_CONST_PASSPORT_SID_);
    }

    public function reset_password($passport, $old_password, $new_password)
    {
        $rows = self::update(
            array('md5_passwd' => md5($new_password)),
            array('passport' => $passport, 'md5_passwd' => md5($old_password))
        );

        return $rows > 0;
    }

	/*
	 * 生成自动登录到SOHU PASSPORT的URL地址
	 *
	 * @param	string	$passport  : 登录帐户
	 * @param	string	$return_url: 登录完成后回跳的地址
	 * @param	string	$passwd    : 登录密码
	 * @param	string	$pwd_type  : 密码类型: NULL => 明文, 'MD5' => md5()
	 */
	public static function url_auto_login ($passport, $return_url, $passwd, $pwd_type = NULL)
	{
		$appid    = Kohana::config('passport.sohu.appid');
		$password = $passwd;
		if (strtolower($pwd_type) == 'md5')
			$md5passwd= $passwd;
		else
			$md5passwd = md5($passwd);
		$return_url = trim(strval($return_url));

		$return_url = 'http://'. site::domain() . '/passport/login_callback?referer=' . $return_url;
		$return_url = "http://passport.sohu.com/sso/login_js.jsp?userid={$passport}&password={$md5passwd}&persistentcookie=1&pwdtype=1&appid={$appid}&ru={$return_url}";

		return $return_url;
	}

	/*
	 * 认证检测
	 *
	 * @param	string	$passport
	 * @param	string	$md5_passwd: md5($passwd)
	 * @param	strign	$auth
	 * @return	boolean
	 */
	public static function check_auth ($passport, $md5_passwd, $auth)
	{
		$md5_str  = md5(strtolower($passport) .
				Kohana::config('passport.email.token'));

		if (empty($passport) OR $auth != $md5_str)
			return FALSE;
		else
			return TRUE;
	}


	/*
	 * 返回登录界面的input[userid]的提示信息
	 *
	 * @return: string (login prompt)
	 * @author: xiaoliangyang 2010-09-03
	 */
	public static function login_prompt () {
		if (NULL === self::register_cookie())
			return '输入手机号或者邮箱';
		else
			return '输入邮箱地址';
	}

	/**
	 * 返回是否是有效的昵称
	 *
	 * @param	string	$nick
	 * @param	string	$message: 昵称无效的原因
	 * @return	boolean
	 */
	public static function valid_nickname ($nickname)
	{
		$len = utf8::strlen($nickname);
		if ($len < 2 || $len > 12)
			throw new Exception_Invalid("昵称长度无效, $nickname");

		$nickname = strtolower($nickname);
		if (! preg_match("/^[\x80-\xff\w]+$/", $nickname))
			throw new Exception_Invalid("昵称只能使用中文，字母，数字");

        $status = 0;
		switch ($status)
		{
		case 0:
			return TRUE;
			break;

		case 1:
			Kohana::$log->add(Log::ERROR, 'API ARGS ERROR: valid_nickname');
			throw new Exception_Invalid("昵称已被占用");
			break;

		case 2:
			Kohana::$log->add(Log::ERROR, 'API CODE ERROR: valid_nickname');
			throw new Exception_Invalid("昵称已被占用");
			break;

		case 3:
			throw new Exception_Invalid("昵称已被占用");
			break;

		case 4:
			// 敏感词
			throw new Exception_Invalid("昵称已被占用");
			break;

		case 5:
			// 受保护
			throw new Exception_Invalid("昵称已被占用");
			break;

		case 6:
		default:
			// 系统错误
			Kohana::$log->add(Log::ERROR, 'API SYS ERROR: valid_nickname');
			throw new Exception_Invalid("昵称已被占用");
			break;
		}

		return TRUE;
	}


	/*
	 * 再次发送激活邮件;
	 */
	public function send_mail($passport, $passwd, $nickname, $return_url)
	{
		// 生成账户激活地址
		$activate_url = $this->build_activate_url2 ($passport, $passwd, $return_url);

		// 发送激活邮件
		$this->send_activate_email ($passport, $nickname, $activate_url);
	}

	/*
	 * 生成激活账户的URL地址
	 *
	 * @param	string 邮件账户
	 * @return	string $url
	 */
	private function build_activate_url2 ($passport, $passwd, $return_url)
	{
		$pwd  = $passwd;
		$auth = md5(strtolower($passport) .
				Kohana::config('passport.email.token'));

		$url  = "http://" . site::domain('member') .
				"/passport/activate".
				"?email={$passport}&passwd={$pwd}&auth={$auth}&ru={$return_url}";
		return $url;
	}



	/*
	 * 激活该用户的帐户
	 */
	public function activate ($passport)
	{
		$userMgr = new UserMgrAction();

		if (! $userMgr->activateSohuPassportAccount($passport))
			return FALSE;

		// 设置本地用户帐户的已激活状态

		// 删除现有用户登录的COOKIE
		$ihomePassport = new IhomePassport();
		$ihomePassport->unsetIhomeCookie();

		// 检查用户是否登录，若未登录，则设置成登录状态(自动登录)
		// ...
		// 检查用户是否有订单要确认，若有，跳转到订单确认页
		// ...

		return TRUE;
	}


	/*
	 * 处理用户邮件订阅
	 */
	public function email_subscribe ($email)
	{
		if (! empty($email) && fsutility::isemail($email))
		{
			//$emailSubscriptionAction = new EmailSubscriptionAction();
			//return $emailSubscriptionAction->create($email);
		}
		else
		{
			return FALSE;
		}
	}

	/*
	 * 生成激活账户的URL地址
	 *
	 * @param	string 邮件账户
	 * @return	string $url
	 */
	private function build_activate_url ($passport, $passwd, $return_url)
	{
		$pwd  = md5($passwd);
		$auth = md5(strtolower($passport) .
				Kohana::config('passport.email.token'));

		$url  = "http://" . site::domain('member') .
				"/passport/activate".
				"?email={$passport}&passwd={$pwd}&auth={$auth}&ru={$return_url}";
		return $url;
	}

	/*
	 * 发送激活邮件
	 *
	 *		若搜狐域的账户，则跳过邮件激活的流程，直接激活。
	 *		否则发送激活邮件
	 *
	 * @param	string $email
	 * @param	string $url : 用户点击后，会激活账户的地址
	 * @return  void
	 */
	private function send_activate_email ($passport, $nickname, $url)
	{
		if (Util::isSohuDomainEmail($passport))
		{
			Request::$current->redirect($url);
		}
		else
		{
			$message = View::factory(
				'smarty:passport/email/register_activate',
				array(
					'url'      => $url,
					'nickname' => $nickname,
				))->render();


			Notice::factory('email')
				->to($passport)
				->subject('搜狐装修网激活邮件')
				->message($message)
				->send();
		}
	}

	/*
	 * 获取用户的是否使用Passport注册的Cookie标示
	 *
	 * @return: int (cookie value), NULL if not exists
	 * @author: xiaoliangyang 2010-09-03
	 */
	private static function register_cookie () {
		$k = Kohana::config('passport.cookie.register');
		if (isset($_COOKIE[$k]) AND !empty($_COOKIE[$k]))
			return intval($_COOKIE[$k]);
		else
			return NULL;
	}

    private static function insert ($record)
    {
        list($insert_id, $rows) = DB::insert(self::_CONST_TB_DEFAULT_)
            ->columns(array_keys  ($record))
            ->values (array_values($record))
            ->execute();

        return TRUE;
    }

    private static function count ($infos)
    {
        $query = DB::select(array('count("passport")', 'count'))
            ->from(self::_CONST_TB_DEFAULT_);

        foreach ($infos as $k => $v)
            $query->where($k, '=', $v);

        $r = $query->execute();
        return (int) ($query->execute()->get('count'));
    }

    private static function update ($info, $where)
    {
        $query = DB::update(self::_CONST_TB_DEFAULT_)
            ->set($info);

        foreach ($where as $k => $v)
            $query->where($k, '=', $v);

        $rows  = $query->execute();
        return $rows;
    }
}
